package com.yanqu.road.server.manger.activity.peakstronghold;

import com.yanqu.road.entity.activity.ActivityConfig;
import com.yanqu.road.entity.activity.ActivityInfo;
import com.yanqu.road.entity.activity.huashigang.HuaShiGangFloorConfig;
import com.yanqu.road.entity.activity.peakstronghold.PeakStrongholdUploadMarkData;
import com.yanqu.road.entity.activity.peakstronghold.config.PeakStrongHoldConfig;
import com.yanqu.road.entity.activity.peakstronghold.config.ePeakStrongholdStageType;
import com.yanqu.road.entity.activity.peakstronghold.config.PeakStrongholdBaseConfig;
import com.yanqu.road.entity.activity.peakstronghold.config.PeakStrongholdDonateConfig;
import com.yanqu.road.entity.activity.peakstronghold.config.PeakStrongholdTimeConfig;
import com.yanqu.road.entity.config.goods.GoodsInfo;
import com.yanqu.road.entity.config.goods.OpenGoodsBagResult;
import com.yanqu.road.entity.enums.eActivityType;
import com.yanqu.road.entity.enums.eUnionSyncType;
import com.yanqu.road.entity.player.UserPatrons;
import com.yanqu.road.entity.servercenter.ServerInfo;
import com.yanqu.road.entity.union.activitygroup.UnionActivityGroup;
import com.yanqu.road.entity.union.activitygroup.UnionActivityGroupUnion;
import com.yanqu.road.entity.union.activitygroup.UnionActivityGroupUser;
import com.yanqu.road.entity.union.cross.CrossUnionInfo;
import com.yanqu.road.entity.union.cross.CrossUnionMember;
import com.yanqu.road.logic.helper.UnionActivityGroupHelper;
import com.yanqu.road.logic.pb.UnionBasePb;
import com.yanqu.road.logic.bussiness.activity.PeakStrongholdActivityBusiness;
import com.yanqu.road.logic.rank.UnionRankMsgModel;
import com.yanqu.road.message.YanQuMessage;
import com.yanqu.road.pb.activity.PeakStrongholdWarProto;
import com.yanqu.road.pb.activity.StrongholdWarProto;
import com.yanqu.road.pb.union.cross.CrossUnionProto;
import com.yanqu.road.server.GameServer;
import com.yanqu.road.server.TempMgr;
import com.yanqu.road.server.gameplayer.GamePlayer;
import com.yanqu.road.server.gameplayer.module.activity.peakstronghold.PeakStrongholdModule;
import com.yanqu.road.server.manger.ServerListMgr;
import com.yanqu.road.server.manger.activity.ActivityMgr;
import com.yanqu.road.server.manger.activity.CommonActivityRankMgr;
import com.yanqu.road.server.manger.activity.DigMgr;
import com.yanqu.road.server.manger.activity.NormalActivityMgr;
import com.yanqu.road.server.manger.config.GoodsBagMgr;
import com.yanqu.road.server.manger.player.GamePlayerMgr;
import com.yanqu.road.server.manger.system.CommonMgr;
import com.yanqu.road.server.manger.union.CrossUnionMgr;
import com.yanqu.road.server.manger.union.GameUnionActivityGroupMgr;
import com.yanqu.road.server.protocol.CrossProtocol;
import com.yanqu.road.server.pb.PeakStrongholdActivityWarPb;
import com.yanqu.road.server.protocol.Protocol;
import com.yanqu.road.utils.YanQuMessageUtils;
import com.yanqu.road.utils.config.Config;
import com.yanqu.road.utils.date.DateHelper;
import com.yanqu.road.utils.property.Property;
import com.yanqu.road.utils.string.StringUtils;

import java.math.BigInteger;
import java.util.List;
import java.util.Map;

import java.util.*;
import java.util.concurrent.locks.Lock;
import java.util.concurrent.locks.ReentrantLock;

public class PeakStrongholdActivityMgr extends TempMgr {

    static PeakStrongHoldConfig config;
    private static PeakStrongholdGroup uploadMarkDataGroup;
    private static final Lock markDataLock = new ReentrantLock();

    public static ActivityInfo getActivityInfo() {
        if (config == null) {
            return null;
        }
        return config.getActivityInfo();
    }

    public static PeakStrongHoldConfig getConfig() {
        return config;
    }

    public static PeakStrongholdUploadMarkData getUploadMarkData(int unionGroup) {
        if (null == config) {
            return null;
        }
        if (unionGroup == UnionActivityGroupHelper.NO_GROUP_ID){
            return null;
        }

        if (uploadMarkDataGroup == null) {
            return null;
        }

        return uploadMarkDataGroup.getUploadMarkData(unionGroup);
    }

    public static void reloadActivityData() {
        getLogger().info("reload PeakStrongholdActivity start");
        List<ActivityInfo> openActivityInfoList = NormalActivityMgr.getOpenActivityInfoList(eActivityType.PeakStrongHold.getValue());
        if (openActivityInfoList.isEmpty()) {
            getLogger().info("no PeakStrongholdActivity in show time");
            config = null;
            uploadMarkDataGroup = null;
        } else {
            ActivityInfo tempActivityInfo;
            tempActivityInfo = openActivityInfoList.get(0);
            int tmpActivityId = tempActivityInfo.getActivityId();
            PeakStrongHoldConfig configTemp = new PeakStrongHoldConfig();
            configTemp.setActivityInfo(tempActivityInfo);

            //读配置
            Map<Integer, HuaShiGangFloorConfig> tempDesertConfigMap = PeakStrongholdActivityBusiness.getPeakStrongholdDesertConfig(tmpActivityId);
            Map<Integer, PeakStrongholdTimeConfig> tempTimeConfigMap = PeakStrongholdActivityBusiness.getPeakStrongholdTimeConfig(tmpActivityId);
            Map<Integer, PeakStrongholdBaseConfig> tempBaseConfigMap = PeakStrongholdActivityBusiness.getPeakStrongholdBaseConfig(tmpActivityId);
            Map<Integer, PeakStrongholdDonateConfig> tempDonateConfigMap = PeakStrongholdActivityBusiness.getPeakStrongholdDonateConfig(tmpActivityId);


            Map<String, ActivityConfig> activityConfigMap = NormalActivityMgr.getActivityConfigMap(tmpActivityId);
            configTemp.initConfig(activityConfigMap, tempDesertConfigMap, tempTimeConfigMap, tempBaseConfigMap, tempDonateConfigMap);
            if (!configTemp.timeCheckSuccess()) {
                //活动的endTime如果和淘汰赛的结束时间不一致报个错，不一致会导致排行领奖时和淘汰赛时间对不上
                getLogger().error("巅峰据点战的活动结束时间{}!=淘汰赛结束时间{}", configTemp.getActivityInfo().getEndTime(), configTemp.getEliminateEndTime());
            }
            Map<Integer, PeakStrongholdUploadMarkData> tempMarkDataMap = PeakStrongholdActivityBusiness.getPeakStrongholdUploadMarkData(tmpActivityId);
            PeakStrongholdGroup tempPeakMarkGroup = new PeakStrongholdGroup(tmpActivityId);
            tempPeakMarkGroup.setUploadMarkDataMap(tempMarkDataMap);

            config = configTemp;
            uploadMarkDataGroup = tempPeakMarkGroup;
            DigMgr.loadActivityCommonConfig(tmpActivityId);

            playerReloadActivity();
            reloadCross(config.getActivityInfo());
        }
        getLogger().info("reload PeakStrongholdActivity finish");
    }

    private static void reloadCross(ActivityInfo activityInfo) {
        if (activityInfo != null) {
            Map<Integer, UnionActivityGroup> groupMap = GameUnionActivityGroupMgr.getGroupMap(activityInfo.getActivityId());
            if (groupMap == null) {
                return;
            }
            for (UnionActivityGroup unionActivityGroup : groupMap.values()) {
                StrongholdWarProto.CrossStrongholdReloadReqMsg.Builder req = StrongholdWarProto.CrossStrongholdReloadReqMsg.newBuilder();
                req.setActivityId(activityInfo.getActivityId());
                req.setStartShowTime(activityInfo.getBeginShowTime());
                req.setStartTime(activityInfo.getBeginTime());
                req.setEndTime(activityInfo.getEndTime());
                req.setEndShowTime(activityInfo.getEndShowTime());
                GamePlayerMgr.sendUnionActivityGroupPacket(Protocol.C_PEAK_STRONGHOLD_RELOAD_ACTIVITY, req, 0, activityInfo.getActivityId(), unionActivityGroup.getGroupId());
            }
        }
    }

    private static void playerReloadActivity() {
        List<GamePlayer> playerList = GamePlayerMgr.getCopyPlayerList();
        playerList.forEach(player -> {
            player.getModule(PeakStrongholdModule.class).afterLogin();
        });
    }

    public static PeakStrongholdWarProto.SyncPeakStrongholaActivityMsg.Builder getConfigMsg(String language){
        if(config != null && config.getActivityInfo() != null && ActivityMgr.activityInShowTime(config.getActivityInfo())){
            PeakStrongholdWarProto.SyncPeakStrongholaActivityMsg.Builder syncMsg = PeakStrongholdActivityWarPb.getPeakStrongholdActivityMsg(
                    config.getDesertConfigMap(),
                    config.getDonateConfigMap(),
                    config.getBaseConfigMap(),
                    config.getTimeConfigMap(),
                    language);
            return syncMsg;
        }
        return null;
    }

    public static Property getMammonUseReward(int goodsId) {
        int boxId = 0;
        try {
            GoodsInfo goodsInfo = CommonMgr.getGoodsInfo(goodsId);
            if (goodsInfo != null) {
                boxId = goodsInfo.getParamList().get(0).intValue();
            }
        } catch (Exception e) {

        }
        OpenGoodsBagResult randomGoods = GoodsBagMgr.getRandomGoods(boxId);
        return randomGoods.getReward();
    }

    @Override
    public boolean init() throws Exception {
        return true;
    }

    @Override
    public boolean reloadConfig() throws Exception {
        return true;
    }

    @Override
    public boolean reloadData() throws Exception {
        return true;
    }

    @Override
    public boolean stop() {
        return false;
    }

    @Override
    public boolean save() {
        if (null != uploadMarkDataGroup) {
            uploadMarkDataGroup.save();
        }

        return true;
    }

    /**
     * 更新联盟数据,更新赚速,报名阶段才需要更新
     *
     * @param unionUid
     * @param unionInfo
     */
    public static void unionChange(int syncType, String unionUid, CrossUnionInfo unionInfo, List<CrossUnionMember> memberList) {
        try {
            if (null == config) {
                return;
            }
            ActivityInfo activityInfo = config.getActivityInfo();
            if (!ActivityMgr.activityInShowTime(activityInfo)) {
                return;
            }
            if (config.getStageType() == ePeakStrongholdStageType.Prepare || config.getStageType() == ePeakStrongholdStageType.InBattle) {
                if (syncType == eUnionSyncType.Normal.getValue() || syncType == eUnionSyncType.SetPosition.getValue()) {
                    // 在淘汰赛才传
                    if (!canUnionInBattle(unionUid) && !isOutUnion(unionUid)) {
                        return;
                    }
                    PeakStrongholdWarProto.CrossUpdateUnionBaseMsgReq.Builder builder = PeakStrongholdWarProto.CrossUpdateUnionBaseMsgReq.newBuilder();
                    builder.setActivityId(activityInfo.getActivityId());
                    builder.setUnionUid(unionUid);
                    builder.setUnionInfo(UnionBasePb.parseUnionBaseTempMsg(CrossUnionMgr.parseUnionBaseInfo(unionInfo)));
                    builder.setUpdateTime(DateHelper.getCurrentTime());
                    int unionGroup = GameUnionActivityGroupMgr.getGroupId(builder.getActivityId(), unionUid);
                    GamePlayerMgr.sendUnionActivityGroupPacket(CrossProtocol.C_PEAK_STRONGHOLD_UPDATE_UNION_BASE, builder, 0, builder.getActivityId(), unionGroup);
                }
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    //活动刚加载时跨服通知的取商会数据
//    public static boolean notifyUpdateAbility() {
//        if (!CrossUnionMgr.isAllSync()) {
//            if (Config.isDebug()) {
//                getLogger().info("notifyUpdateAbility, 商会跨服还没有同步完数据！");
//            }
//            return false;
//        }
//        PeakStrongholdUploadMarkData markData = getUploadMarkData();
//        if (null == markData) {
//            return false;
//        }
//        synchronized (markData) {
//            //markData.getWaitUploadAbilityUsers().clear();
//            for (CrossUnionInfo unionInfo : CrossUnionMgr.getUnionInfoMap().values()) {
//                for (CrossUnionMember member : CrossUnionMgr.getUnionMemberMap(unionInfo.getUnionUid()).values()) {
//                    if (member.getServerId() != GameServer.getInstance().getServerId()) {
//                        continue;
//                    }
//                    if (!markData.getWaitUploadAbilityUsers().contains(member.getUserId())){
//                        markData.getWaitUploadAbilityUsers().addLast(member.getUserId());
//                    }
//                    if (Config.isDebug()) {
//                        getLogger().info("玩家{}商会{}加入等待取赚力！", member.getUserId(), member.getUnionUid());
//                    }
//                }
//            }
//            markData.setUpdateOption();
//        }
//        return true;
//    }

    //取需要上传数据的商会成员,
    @Deprecated
    public static List<Long> popWaitTakeAbilityMembers(int takeCount) {
        List<Long> userIds = new ArrayList<>();
//        if (!CrossUnionMgr.isAllSync()|| !canNotifyCrossActivity) {
//            return userIds;
//        }
//        PeakStrongholdUploadMarkData markData = getUploadMarkData();
//        if (null == markData || markData.getWaitUploadAbilityUsers().isEmpty()) {
//            return userIds;
//        }
//
//        synchronized (markData) {
//            while (!markData.getWaitUploadAbilityUsers().isEmpty()) {
//                Long userId = markData.getWaitUploadAbilityUsers().pop();
//                userIds.add(userId);
//
//                if (--takeCount <= 0) {
//                    break;
//                }
//            }
//        }
//
//        markData.setUpdateOption();
//
//        if (markData.getWaitUploadAbilityUsers().isEmpty() && config.getStageType() != ePeakStrongholdStageType.Registration) {
//            //不在报名阶段传完数据后，要通知跨服传完了
//            confirmUpdateAbilityEnd();
//        }
        return userIds;
    }

    //新的需要传数据的商会成员
    @Deprecated
    public static void addWaitTakeAbilityMembers(long userId, String unionId) {
//        if (config == null || !ActivityMgr.activityInTime(config.getActivityInfo())) {
//            //不在活动时间
//            return;
//        }
//        if (config.getStageType() != ePeakStrongholdStageType.Registration) {
//            //不在报名期
//            return;
//        }
//
//        PeakStrongholdUploadMarkData markData = getUploadMarkData();
//        if (null == markData) {
//            return;
//        }
//        synchronized (markData) {
//            if (markData.getWaitUploadAbilityUsers().contains(userId)) {
//                //已经在等待上传
//                return;
//            }
//
//            if (StringUtils.isNullOrEmpty(unionId)) {
//                //不在商会了
//                markData.getWaitUploadAbilityUsers().remove(userId);
//                return;
//            }
//
//            markData.getWaitUploadAbilityUsers().addLast(userId);
//            markData.setUpdateOption();
//        }
    }

    @Deprecated
    public static void confirmUpdateAbilityEnd() {
//        PeakStrongholdUploadMarkData markData = getUploadMarkData();
//        if (null == markData) {
//            return;
//        }
//        int remainCount = markData.getWaitUploadAbilityUsers().size();
//        PeakStrongholdWarProto.CrossPeakHoldUpdateDataEndConfirmResp.Builder syncMsg = PeakStrongholdWarProto.CrossPeakHoldUpdateDataEndConfirmResp.newBuilder();
//        syncMsg.setActivityId(config.getActivityInfo().getActivityId());
//        syncMsg.setServerId(GameServer.getInstance().getServerId());
//        syncMsg.setRemainCount(remainCount);
//        ServerInfo serverInfo = ServerListMgr.getServerInfo(GameServer.getInstance().getServerId());
//        syncMsg.setOpenTime(serverInfo.getOpenTime());
//        YanQuMessage pbMsg = YanQuMessageUtils.buildMessage(Protocol.C_PEAK_STRONGHOLD_NOTIFY_UPDATE_DATA_END_CONFIRM, syncMsg);
//        GamePlayerMgr.sendPacket(0, pbMsg);
    }

    public static void updateEliminateUnionList(int round, PeakStrongholdWarProto.CrossPeakHoldEliminateUnionListMsg msg, int unionGroup) {
        //游戏服的商会参与资格会滞后于跨服
        PeakStrongholdUploadMarkData markData = getUploadMarkData(unionGroup);
        if (null == markData) {
            return;
        }
        markData.setRound(round);
        markData.getUnionIds().clear();
        msg.getRiseUpUnionsList().forEach(peakHoldUnionRoundEndMsg -> {
            String unionId = peakHoldUnionRoundEndMsg.getUnionId();
            markData.getUnionIds().add(unionId);

            if (msg.hasIsBroadcast() && msg.getIsBroadcast()) {
                if (Config.isDebug()) {
                    getLogger().info("巅峰据点战 商会晋级广播,商会={}", unionId);
                }
                //广播给商会在线成员商会晋级
                for (CrossUnionMember member : CrossUnionMgr.getUnionMemberMap(unionId).values()) {
                    if (member.getServerId() != GameServer.getInstance().getServerId()) {
                        continue;
                    }
                    GamePlayer player = GamePlayerMgr.getOnlinePlayer(member.getUserId());
                    if (null == player) {
                        continue;
                    }
                    player.sendPacket(Protocol.U_PEAK_STRONGHOLD_ELIMINATE_UNION_RISE, peakHoldUnionRoundEndMsg.toBuilder());
                    if (Config.isDebug()) {
                        getLogger().info("巅峰据点战 商会晋级广播,玩家={}，商会={}", player.getUserId(), unionId);
                    }
                }
            }
        });

        markData.setOutUnionIds(msg.getOutUnionIdsList());//淘汰的商会

        markData.setUpdateOption();

        if (msg.hasIsBroadcast() && msg.getIsBroadcast()) {
            msg.getNotRiseUpUnionsList().forEach(peakHoldUnionRoundEndMsg -> {
                //广播给商会在线成员商会未晋级消息
                String unionId = peakHoldUnionRoundEndMsg.getUnionId();
                if (Config.isDebug()) {
                    getLogger().info("巅峰据点战 商会未晋级广播,商会={}", unionId);
                }
                for (CrossUnionMember member : CrossUnionMgr.getUnionMemberMap(unionId).values()) {
                    if (member.getServerId() != GameServer.getInstance().getServerId()) {
                        continue;
                    }
                    GamePlayer player = GamePlayerMgr.getOnlinePlayer(member.getUserId());
                    if (null == player) {
                        continue;
                    }
                    player.sendPacket(Protocol.U_PEAK_STRONGHOLD_ELIMINATE_UNION_RISE, peakHoldUnionRoundEndMsg.toBuilder());
                    if (Config.isDebug()) {
                        getLogger().info("巅峰据点战 商会未晋级广播,玩家={}，商会={}", player.getUserId(), unionId);
                    }
                }
            });
        }
    }

    //是否有参赛资格
    public static boolean canUnionInBattle(String unionId) {
        if (config == null) {
            return false;
        }
        int unionGroup = GameUnionActivityGroupMgr.getGroupId(config.getActivityInfo().getActivityId(), unionId);
        if (unionGroup == UnionActivityGroupHelper.NO_GROUP_ID){
            return false;
        }
        PeakStrongholdUploadMarkData markData = getUploadMarkData(unionGroup);
        if (null == markData) {
            return false;
        }
        return markData.getUnionIds().contains(unionId);
    }

    //是否为淘汰掉的商会
    public static boolean isOutUnion(String unionId){
        if (config == null) {
            return false;
        }
        int unionGroup = GameUnionActivityGroupMgr.getGroupId(config.getActivityInfo().getActivityId(), unionId);
        if (unionGroup == UnionActivityGroupHelper.NO_GROUP_ID){
            return false;
        }
        PeakStrongholdUploadMarkData markData = getUploadMarkData(unionGroup);
        if (null == markData) {
            return false;
        }
        return markData.getOutUnionIds().contains(unionId);
    }

    //通知上传防守门客
    public static void notifyUpdateDefendPatrons(int unionGroup) {
        PeakStrongholdUploadMarkData markData = getUploadMarkData(unionGroup);
        if (null == markData) {
            return;
        }
        synchronized (markData) {
            //活动跨服过来的通知,如果游戏服先启动,能收到通知，游戏服后启动,自己通知自己
            markData.getWaitUploadDefendUsers().clear();
            UnionActivityGroup groupData = GameUnionActivityGroupMgr.getGroupData(markData.getActivityId(), markData.getUnionGroup());
            if (groupData == null) {
                return;
            }
            for (UnionActivityGroupUnion groupUnion : groupData.getUnionDataMap().values()) {
                if (!markData.getUnionIds().contains(groupUnion.getUnionUid())){
                    continue;
                }
                for (UnionActivityGroupUser groupUser : groupUnion.getUserMap().values()) {
                    if (groupUser.getServerId() == GameServer.getInstance().getServerId()){
                        markData.getWaitUploadDefendUsers().addLast(groupUser.getUserId());
                    }
                }
            }
        }
    }

    //取需要上传数据的商会成员,
    public static Map<Integer, List<Long>> popWaitTakeDefendPatronsMembers(int takeCount) {
        Map<Integer, List<Long>> dataMap = new HashMap<>();
        if (!CrossUnionMgr.isAllSync()) {
            return dataMap;
        }

        Map<Integer, PeakStrongholdUploadMarkData> uploadMarkDataMap = uploadMarkDataGroup.getUploadMarkDataMap();
        for (PeakStrongholdUploadMarkData markData : uploadMarkDataMap.values()) {
            List<Long> userIds = new ArrayList<>();
            if (markData.getWaitUploadDefendUsers().isEmpty()) {
                continue;
            }
            synchronized (markData) {
                while (!markData.getWaitUploadDefendUsers().isEmpty()) {
                    Long userId = markData.getWaitUploadDefendUsers().pop();
                    userIds.add(userId);

                    if (--takeCount <= 0) {
                        break;
                    }
                }
            }

            dataMap.put(markData.getUnionGroup(), userIds);

            if (markData.getWaitUploadDefendUsers().isEmpty() &&
                    (config.getStageType() != ePeakStrongholdStageType.Prepare || markData.getRound() != config.getRound())) {
                //不在报名阶段传完数据后，要通知跨服传完了
                confirmUpdateDefendPatronsEnd(markData.getUnionGroup());
            }
            markData.setUpdateOption();
        }

        return dataMap;
    }

    //新的需要传数据的商会成员
    public static void addWaitTakeDefendMembers(long userId) {
        if (config == null || !ActivityMgr.activityInTime(config.getActivityInfo())) {
            //不在活动时间
            return;
        }
        String unionId = GameUnionActivityGroupMgr.getUnionUid(config.getActivityInfo().getActivityId(), userId);
        int unionGroup = GameUnionActivityGroupMgr.getGroupId(config.getActivityInfo().getActivityId(), unionId);
        if (config.getStageType() != ePeakStrongholdStageType.Prepare) {
            //不在准备期
            return;
        }
        if (!canUnionInBattle(unionId)) {
            return;
        }
        PeakStrongholdUploadMarkData markData = getUploadMarkData(unionGroup);
        if (null == markData) {
            return;
        }
        synchronized (markData) {
            if (markData.getWaitUploadDefendUsers().contains(userId)) {
                //已经在等待上传
                return;
            }

            if (StringUtils.isNullOrEmpty(unionId)) {
                //不在商会了
                markData.getWaitUploadDefendUsers().remove(userId);
                return;
            }

            markData.getWaitUploadDefendUsers().addLast(userId);
        }
        markData.setUpdateOption();
    }

    public static void confirmUpdateDefendPatronsEnd(int unionGroup) {
        PeakStrongholdUploadMarkData markData = getUploadMarkData(unionGroup);
        if (null == markData) {
            return;
        }
        int remainCount = markData.getWaitUploadDefendUsers().size();
        PeakStrongholdWarProto.CrossPeakHoldUpdateDataEndConfirmResp.Builder syncMsg = PeakStrongholdWarProto.CrossPeakHoldUpdateDataEndConfirmResp.newBuilder();
        syncMsg.setActivityId(config.getActivityInfo().getActivityId());
        syncMsg.setServerId(GameServer.getInstance().getServerId());
        syncMsg.setRemainCount(remainCount);
        ServerInfo serverInfo = ServerListMgr.getServerInfo(GameServer.getInstance().getServerId());
        syncMsg.setOpenTime(serverInfo.getOpenTime());
        GamePlayerMgr.sendUnionActivityGroupPacket(Protocol.C_PEAK_STRONGHOLD_NOTIFY_UPDATE_DATA_END_CONFIRM, syncMsg, 0, markData.getActivityId(), unionGroup);
    }

    public static List<UserPatrons> getUserPatronsByEarnSpeedRank(int takeCount, List<UserPatrons> userPatronsList) {
        List<UserPatrons> patrons = new ArrayList<>();
        userPatronsList.sort((o1, o2) -> {
            BigInteger a1 = o1.getAbility();
            BigInteger a2 = o2.getAbility();
            return a2.compareTo(a1);
        });

        for (UserPatrons userPatron : userPatronsList) {
            patrons.add(userPatron);
            if (--takeCount <= 0) {
                break;
            }
        }

        return patrons;
    }

    public static boolean canChangeUnion(String unionId) {
        if (null == config) {
            return true;
        }
        if (config.getStageType() == ePeakStrongholdStageType.EndInShow) {
            return true;
        }
        if (config.getRound() > 0) {
            //回合大于1，说明进入淘汰赛了
            if (canUnionInBattle(unionId) || isOutUnion(unionId)) {
                //商会进入了淘汰赛
                return false;
            }
        }
        return true;
    }

    public static List<String> getEliminateUnionList() {
        if (null == config) {
            return null;
        }
        if (config.getStageType() == ePeakStrongholdStageType.EndInShow) {
            return null;
        }
        List<String> unionIds = new ArrayList<>();
        for (PeakStrongholdUploadMarkData markData : uploadMarkDataGroup.getUploadMarkDataMap().values()) {
            unionIds.addAll(markData.getUnionIds());
        }
        return unionIds;
    }
    public static Property getEliminateKillReward() {
        if (null == config) {
            return null;
        }
        int killItemId = config.getKillItemId();
        OpenGoodsBagResult randomGoods = GoodsBagMgr.getRandomGoods(killItemId);
        return new Property(randomGoods.getReward());
    }

    public static void checkEliminateUnionList() {
        if (!CrossUnionMgr.isAllSync()) {
            return;
        }
        //在淘汰赛期间,如果名单是空的，要找跨服请求
        if (config == null || config.getRound() == 0) {
            //不在淘汰赛期间
            return;
        }
        if (config.getStageType() == ePeakStrongholdStageType.EndInShow) {
            return;
        }
        if (null == uploadMarkDataGroup) {
            return;
        }
        Map<Integer, UnionActivityGroup> groupMap = GameUnionActivityGroupMgr.getGroupMap(config.getActivityInfo().getActivityId());
        if (groupMap == null) {
            return;
        }
        for (UnionActivityGroup unionActivityGroup : groupMap.values()) {
            if (!unionActivityGroup.getServerSet().contains(GameServer.getInstance().getServerId())){
                continue;
            }
            PeakStrongholdUploadMarkData markData = getUploadMarkData(unionActivityGroup.getGroupId());
            if (markData.getUnionIds().isEmpty()) {
                PeakStrongholdWarProto.CrossPeakHoldEliminateUnionListReqMsg.Builder crossMsg = PeakStrongholdWarProto.CrossPeakHoldEliminateUnionListReqMsg.newBuilder();
                crossMsg.setActivityId(config.getActivityInfo().getActivityId());
                GamePlayerMgr.sendUnionActivityGroupPacket(CrossProtocol.C_PEAK_STRONGHOLD_ELIMINATE_UNION_LIST_REQ, crossMsg, 0, config.getActivityInfo().getActivityId(), markData.getUnionGroup());
            }
        }
    }

    //确认活动跨服可以收到消息
//    public static void checkCrossActivityCanNoticy() {
//        if (canNotifyCrossActivity) {
//            return;
//        }
//        if (!CrossUnionMgr.isAllSync()) {
//            return;
//        }
//        if (config == null) {
//            return;
//        }
//
//        PeakStrongholdWarProto.CrossPeakHoldEliminateUnionListReqMsg.Builder crossMsg = PeakStrongholdWarProto.CrossPeakHoldEliminateUnionListReqMsg.newBuilder();
//        crossMsg.setActivityId(config.getActivityInfo().getActivityId());
//        YanQuMessage message = YanQuMessageUtils.buildMessage(CrossProtocol.C_PEAK_STRONGHOLD_CAN_NOTIFY_REQ, crossMsg);
//        GamePlayerMgr.sendPacket(0, message);
//    }

//    public static void setCanNotifyCrossActivity() {
//        canNotifyCrossActivity = true;
//    }

    /**
     * 检查有没有缓存到报名期排行
     */
    public static void checkRegistrationList() {
        ActivityInfo activityInfo = getActivityInfo();
        if (activityInfo == null) {
            return;
        }

        PeakStrongholdTimeConfig timeConfig = config.getTimeConfig(ePeakStrongholdStageType.Registration.getValue(), 0);
        if (null == timeConfig) {
            return;//报错取不到配置！异常！
        }
        int rankNumLimit = Integer.parseInt(timeConfig.getParam());
        if (!UnionActivityGroupHelper.needGroup(activityInfo)) {
            UnionRankMsgModel model = CommonActivityRankMgr.getUnionRankMsgModel(activityInfo.getActivityId());
            if (null != model) {
                model.setRankNum(rankNumLimit + 20);
                model.setActivityEndTime(activityInfo.getEndShowTime());
                if (model.getRankListMsg().getRankListCount() == 0 && !model.isInReq()) {
                    CrossUnionProto.CrossUnionGetMaxAbilityUnionRankListReq.Builder crossReqMsg = CrossUnionProto.CrossUnionGetMaxAbilityUnionRankListReq.newBuilder();
                    crossReqMsg.setActivityId(activityInfo.getActivityId());
                    crossReqMsg.addAllServerIds(activityInfo.getServerIdList());
                    crossReqMsg.setRankNum(model.getRankNum());
                    crossReqMsg.setActivityEndTime(activityInfo.getEndShowTime());
                    GamePlayerMgr.sendPacket(0, YanQuMessageUtils.buildMessage(Protocol.C_UNION_GET_MAX_ABILITY_UNION_RANK_LIST, crossReqMsg));
                }
            }
        } else {
            Map<Integer, UnionActivityGroup> groupMap = GameUnionActivityGroupMgr.getGroupMap(activityInfo.getActivityId());
            if (groupMap == null) {
                return;
            }
            for (UnionActivityGroup unionActivityGroup : groupMap.values()) {
                UnionRankMsgModel model = CommonActivityRankMgr.getUnionRankMsgModelByGroup(activityInfo.getActivityId(), unionActivityGroup.getGroupId());
                if (null != model) {
                    model.setRankNum(rankNumLimit + 20);
                    model.setActivityEndTime(activityInfo.getEndShowTime());
                    if (model.getRankListMsg().getRankListCount() == 0 && !model.isInReq()) {
                        CrossUnionProto.CrossUnionGetMaxAbilityUnionRankListReq.Builder crossReqMsg = CrossUnionProto.CrossUnionGetMaxAbilityUnionRankListReq.newBuilder();
                        crossReqMsg.setActivityId(activityInfo.getActivityId());
                        crossReqMsg.addAllServerIds(activityInfo.getServerIdList());
                        crossReqMsg.setRankNum(model.getRankNum());
                        crossReqMsg.setActivityEndTime(activityInfo.getEndShowTime());
                        crossReqMsg.setGroupId(unionActivityGroup.getGroupId());
                        GamePlayerMgr.sendPacket(0, YanQuMessageUtils.buildMessage(Protocol.C_UNION_GET_MAX_ABILITY_UNION_RANK_LIST, crossReqMsg));
                    }
                }
            }
        }

    }
}

